package com.cskaoyan.service;

import com.cskaoyan.mapper.*;
import com.cskaoyan.module.bean.BaseRespVo;
import com.cskaoyan.module.bean.bo.OrderRefundBo;
import com.cskaoyan.module.bean.bo.OrderShipBo;
import com.cskaoyan.module.bean.param.BaseParam;
import com.cskaoyan.module.bean.vo.*;
import com.cskaoyan.module.pojo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService{

    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;
    @Autowired
    MarketUserMapper userMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Override
    public OrderListData selectOrderList(BaseParam baseParam, Integer userId, String orderStatusArray,
                                         String start, String end, String orderSn) {
        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(baseParam.getPage(),baseParam.getLimit());
        //执行查询过程中拼接分页信息
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (orderSn != null && !"".equals(orderSn)){
            criteria.andOrderSnEqualTo(orderSn);
        }
        if (userId != null && userId!= 0){
            criteria.andUserIdEqualTo(userId);
        }
        if (orderStatusArray != null && !"".equals(orderStatusArray)){
            List<Short> list = new ArrayList<>();
            String[] split = orderStatusArray.split(",");
            for (String orderStatus : split){
                list.add(Short.valueOf(orderStatus));
            }
            criteria.andOrderStatusIn(list);
        }

        if (start != null && !"".equals(start)){
            Date startDate = null;
            try {
                startDate = simpleDateFormat.parse(start);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            criteria.andAddTimeGreaterThanOrEqualTo(startDate);
        }
        if (end != null && !"".equals(end)){
            Date endDate = null;
            try {
                endDate = simpleDateFormat.parse(end);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            criteria.andAddTimeLessThanOrEqualTo(endDate);
        }
        criteria.andDeletedEqualTo(false);

        orderExample.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        List<MarketOrder> marketOrders = orderMapper.selectByExample(orderExample);
        //total、pages、list
        //通过PageHelper帮我们来获得一些和分页相关的信息PageInfo
        //使用其有参构造方法 → 形参写来源于数据库的list
        PageInfo<MarketOrder> pageInfo = new PageInfo<>(marketOrders);
        //list.size() !一定= total   → total ≥ list.size()
        long total = pageInfo.getTotal();//拿到满足条件的总的数据量（不考虑分页）
        int pages = pageInfo.getPages();
        //long total,Integer pages,Integer limit,Integer page,List list
        return OrderListData.data(total, pages, baseParam.getLimit(), baseParam.getPage(), marketOrders);
    }

    @Override
    public List<OrderChannelVo> selectOrderChannel() {
        return orderMapper.selectChannel();
    }


    /**
     * 查询 order  orderGoods user表
     * @param orderId
     * @return 返回相应的数据
     */
    @Override
    public OrderDetailVo selectOrderOrUserOrGoodsList(Integer orderId) {

        //获取order列表信息
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        //获取orderGoods列表信息
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        //获取user列表信息
        MarketUser marketUser = userMapper.selectByPrimaryKey(marketOrder.getUserId());
        UserOrderDetailVo userOrderDetailVo = new UserOrderDetailVo();
        userOrderDetailVo.setCode(marketUser.getAvatar());
        userOrderDetailVo.setNickname(marketUser.getNickname());
        return OrderDetailVo.data(marketOrder,marketOrderGoods,userOrderDetailVo);
    }


    /**
     * order 逻辑删除
     * @param orderId
     * @return
     */
    @Override
    public int updateOrderDeleted(String orderId) {

        String[] split = orderId.split(":");
        String[] strings = split[1].split("}");
        int id = Integer.parseInt(strings[0]);

        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(id);
        marketOrder.setDeleted(true);

        return orderMapper.updateByPrimaryKey(marketOrder);
    }


    /**
     *修改订单退款信息
     * @param orderRefundBo
     * @return
     */
    @Override
    public int orderRefund(OrderRefundBo orderRefundBo) {
//        MarketOrderExample orderExample = new MarketOrderExample();
//        MarketOrderExample.Criteria criteria = orderExample.createCriteria();

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(Integer.parseInt(orderRefundBo.getOrderId()));
        marketOrder.setRefundAmount(BigDecimal.valueOf(Integer.parseInt(orderRefundBo.getRefundMoney())));
        marketOrder.setRefundType("");
        marketOrder.setRefundContent("");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        sdf.format(date);
        marketOrder.setRefundTime(date);
        marketOrder.setOrderStatus((short) 203);
        return orderMapper.updateByPrimaryKeySelective(marketOrder);
    }


    /**
     * 修改订单发货状态
     * @param orderShipBo
     * @return
     */
    @Override
    public int orderShip(OrderShipBo orderShipBo) {

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderShipBo.getOrderId());
        marketOrder.setShipChannel(orderShipBo.getShipChannel());
        marketOrder.setShipSn(orderShipBo.getShipSn());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        sdf.format(date);
        marketOrder.setShipTime(date);
        marketOrder.setOrderStatus((short) 301);
        return orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public BaseRespVo replyCommentById(Map map) {
        Integer commentId = (Integer) map.get("commentId");
        String content = (String) map.get("content");
         if (content == null){
             return BaseRespVo.commentHasReply();
         }
        MarketComment comment = marketCommentMapper.selectByPrimaryKey(commentId);
        if (comment.getAdminContent() != null){
            return BaseRespVo.commentHasReply();
        }
        MarketComment marketComment = new MarketComment();
        marketComment.setId(commentId);
        marketComment.setAdminContent(content);
        /*MarketCommentExample example = new MarketCommentExample();
        MarketCommentExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(commentId).andContentEqualTo(content);*/
        int i = marketCommentMapper.updateByPrimaryKeySelective(marketComment);
        System.out.println(i);

        return BaseRespVo.ok("成功");
    }
}
